package com.youlai.boot.daily.service.impl;

import com.youlai.boot.core.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.daily.mapper.DailyRecordMapper;
import com.youlai.boot.daily.service.DailyRecordService;
import com.youlai.boot.daily.model.entity.DailyRecord;
import com.youlai.boot.daily.model.form.DailyRecordForm;
import com.youlai.boot.daily.model.query.DailyRecordQuery;
import com.youlai.boot.daily.model.vo.DailyRecordVO;
import com.youlai.boot.daily.converter.DailyRecordConverter;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 日常记录服务实现类
 *
 * @author cuisheng
 * @since 2025-04-02 22:51
 */
@Service
@RequiredArgsConstructor
public class DailyRecordServiceImpl extends ServiceImpl<DailyRecordMapper, DailyRecord> implements DailyRecordService {

    private final DailyRecordConverter dailyRecordConverter;

    /**
     * 获取日常记录分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<DailyRecordVO>} 日常记录分页列表
     */
    @Override
    public SortedMap<LocalDate, List<DailyRecordVO>> getDailyRecordPage(DailyRecordQuery queryParams) {
        queryParams.setCreateBy(SecurityUtils.getUserId().toString());
        List<String> recordDate = queryParams.getRecordDate();
        if (recordDate != null && !recordDate.isEmpty()) {
            if (recordDate.size() != 1) {
                queryParams.setRecordDate(null);
            }else {
                String s = recordDate.get(0);
                s=s.replace("[","").replace("]","");
                try {
                    Long l = Long.parseLong(s)/1000;

                    // 2. 转换为北京时间（UTC+8）
                    ZoneId beijingZone = ZoneId.of("Asia/Shanghai");
                    LocalDate date = Instant.ofEpochSecond(l)
                            .atZone(beijingZone)
                            .toLocalDate();

                    // 3. 获取该日期所在月份的最后一天
                    LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
                    List<String> dateList=new ArrayList<>();
                    dateList.add(date.toString());
                    dateList.add(lastDayOfMonth.toString());
                    queryParams.setRecordDate(dateList);
                }catch (Exception e) {
                    queryParams.setRecordDate(null);
                }
            }
        }else {
            queryParams.setRecordDate(null);
        }
        Page<DailyRecordVO> pageVO = this.baseMapper.getDailyRecordPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        SortedMap<LocalDate,List<DailyRecordVO>> map=new TreeMap<>(Comparator.reverseOrder());
        List<DailyRecordVO> records = pageVO.getRecords();
        if (records != null && !records.isEmpty()) {
            records.forEach(record -> {
                if (map.containsKey(record.getRecordDate())){
                    map.get(record.getRecordDate()).add(record);
                }else {
                    List<DailyRecordVO> list=new ArrayList<>();
                    list.add(record);
                    map.put(record.getRecordDate(),list);
                }
            });
        }
        return map;
    }

    /**
     * 获取日常记录表单数据
     *
     * @param id 日常记录ID
     * @return
     */
    @Override
    public DailyRecordForm getDailyRecordFormData(Long id) {
        DailyRecord entity = this.getById(id);
        return dailyRecordConverter.toForm(entity);
    }
    
    /**
     * 新增日常记录
     *
     * @param formData 日常记录表单对象
     * @return
     */
    @Override
    public boolean saveDailyRecord(DailyRecordForm formData) {
        formData.setCreateBy(SecurityUtils.getUserId().toString());
        formData.setRecordDate(LocalDate.now());
        DailyRecord entity = dailyRecordConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新日常记录
     *
     * @param id   日常记录ID
     * @param formData 日常记录表单对象
     * @return
     */
    @Override
    public boolean updateDailyRecord(Long id,DailyRecordForm formData) {
        DailyRecord entity = dailyRecordConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除日常记录
     *
     * @param ids 日常记录ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteDailyRecords(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的日常记录数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
